package com.gxa.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.medical.common.BizException;
import com.gxa.medical.common.ErrorCode;

import com.gxa.medical.mapper.UserMapper;
import com.gxa.medical.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gxa.medical.entity.pojo.User;
@Service
//开启事务
@Transactional(rollbackFor = Throwable.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

  //用户登录方法

    @Override
    public User login(String phone, String pwd) throws BizException {
        //如果查询成功返回该用户的对象，否则则返回null
        //select * frong tb_user where phone=? and pwd=?
        //创建条件构造器，并生成查询条件
        LambdaQueryWrapper<User> queryWrapper=Wrappers.lambdaQuery(User.class);

        queryWrapper.eq(User::getPhone,phone);
        queryWrapper.eq(User::getPwd,pwd);

        User one = this.getOne(queryWrapper);

        if(one!=null){
            return one;
        }else {
            throw  new BizException(ErrorCode.FAILED_LOGIN);
        }

    }


    @Override
    public User register(User user) throws Exception {
        LambdaQueryWrapper<User> lambaQuery = Wrappers.lambdaQuery(User.class);
        lambaQuery.eq(User::getPhone,user.getPhone());
        User one = this.getOne(
                lambaQuery
        );

        if(one!=null){
//            return null;//FIXME 暂时表示注册失败
            throw  new BizException(ErrorCode.EXIST_PHONE);

        }
        boolean save = this.save(user);
        return user;
    }

}
